import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


@WebServlet("/upFile")
public class UpFile extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码的方式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取站点根目录
        String basePath = getServletContext().getRealPath("/");
        //设置图片路径
        String img = basePath+"copy.jpg";
        System.out.println(img);
        //接收客户端上传的图片
        //获取网络输入流
        InputStream in = req.getInputStream();
        //获取本地文件输出流
        OutputStream out = new FileOutputStream(img);
        byte[] data = new byte[512];
        int len = -1;
        while ((len = in.read(data,0,data.length))!=-1){
            out.write(data,0,len);
            //刷新
            out.flush();
        }
        //给客户端返回
        resp.getWriter().write("文件上传成功");
        in.close();
        out.close();


    }
}
















